package com.example.demo.Service.impl;

import com.example.demo.Service.IOrderService;
import com.example.demo.entity.Orders;
import com.example.demo.entity.OrdersDtl;
import com.example.demo.entity.vo.OrderSelectVo;
import com.example.demo.entity.vo.OrderShoppingCartVo;
import com.example.demo.mapper.OrderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class IOrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;


    @Transactional
    @Override
    public int createOrders(List<Long> shoppingCartIds, Long userId) {

        //查询商品信息
        List<OrderShoppingCartVo> orderShoppingCartVos = orderMapper.list(shoppingCartIds);

        //生成订单主表
        Orders orders = new Orders();
        orders.setOrderNum(UUID.randomUUID().toString());
        orders.setUserId(userId);
        orders.setOrderTime(new Date());
        orderMapper.create(orders);

        //插入详情信息
        List<OrdersDtl> ordersDtls = new ArrayList<>();
        for(OrderShoppingCartVo orderShoppingCartVo:orderShoppingCartVos){
            OrdersDtl ordersDtl = new OrdersDtl();
            BeanUtils.copyProperties(orderShoppingCartVo,ordersDtl);
            ordersDtl.setOrderId(orders.getOrderId());
            ordersDtls.add(ordersDtl);
        }
        orderMapper.batchCreate(ordersDtls);

        //删除购物车

        int rs = orderMapper.deleteByShoppingCartId(shoppingCartIds);

        return rs;
    }

    @Override
    public List<OrderSelectVo> selectOrders(Long userId) {

        return orderMapper.select(userId);

    }
}
